<template>
	<view class="Observewallet" :config="config" :change:config="renderjs.getConfig">
		<HeaderBar title="观察钱包" showBack backgroundColor="#F6F6F6" fixed />

		<view class="contentBox">
			<!-- <form @submit="formSubmit" @reset="formReset"> -->
			<view class="textarea_box">
				<textarea placeholder="输入钱包地址,观察钱包不需要导入私钥,只需导入钱包地址即可.可查看钱包的余额,交易记录等信息
				." placeholder-style="color: #B2B2B2;font-size:24upx" class="textarea" v-model="textarea"
					placeholder-class="placeholder" />
				<view class="controls">
					<view class="paste" @tap="pasteText">
						粘贴
					</view>
					<!-- <view class="keypal" v-show="active!=3">
						KeyPal Card
					</view> -->
				</view>
			</view>
			<view class="form-item">
				<view class="title f28">钱包网络</view>
				<view class="iptStyle pass-ipt">
					<input class="input" v-model="chainNameTitle" name="input" disabled
						placeholder-style="color: #B2B2B2;font-size:24upx" />
				</view>
			</view>
			<view class="form-item">
				<view class="title f28">钱包名称</view>
				<view class="iptStyle pass-ipt">
					<input class="input" v-model="name" name="input" :placeholder="config?.name"
						placeholder-style="color: #B2B2B2;font-size:24upx" maxlength="10"/>
				</view>
			</view>

			<!-- </form> -->
		</view>
		<view class="btn_box">
			<label class="protocol">
				<view class="raido-box" @tap="toggleButton">
					<image src="../../static/images/login/radio-check.png" mode="" class="raido" v-if="checked">
					</image>
					<image src="../../static/images/login/radio.png" mode="" class="raido" v-else></image>
				</view>
				<view class="tilp">
					我已仔细阅读并同意<text>《<text class="text" @tap="protocol">用户协议</text>》</text>
				</view>
			</label>
			<view class="btn" :class="{'disabled':checked}" :data-address="textarea" :data-checked="checked"
				@tap="renderjs.checkAddress">
				确定导入
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				textarea: "",
				name: "",
				checked: false,
				config: {},
			}
		},
		onLoad(options) {
			const configStr = options.configStr || '';
			try {
				// 解码并反序列化 JSON 字符串
				const config = JSON.parse(decodeURIComponent(configStr));
				this.config = config
			} catch (error) {}
		},
		computed: {
			allchains() {
				return this.$store.getters.getAllchains;
			},
			tokendemail() {
				let chainType = this.config?.chainType
				if (chainType == 'ETH') {
					return 18
				} else if (chainType == 'TRON') {
					return 6
				}
			},
			chainNameTitle() {
				return this.config?.chainName
			},
		},

		methods: {
			protocol() {
				uni.navigateTo({
					url: `/pages/protocol/protocol?id=3&title=用户协议`
				})
			},
			toggleButton() {
				this.checked = !this.checked;
			},
			confirm() {
				uni.$db.select('list', { // 普通查询
					from: 'addressList',
					where: [{
						chainId: `= "${this.config.chainId}"`,
						address: `= "${this.textarea}"`,
					}]
				}).then(res => {
					if (res.length == 0) {
						this.importWallet()
					} else {
						this.toast('该地址已存在')
					}
				})

			},
			importWallet() {
				const result = this.allchains.find(chain => chain.chainId == this.config.chainId)?.coin.filter(coin => coin
					.contract == this.$config.defaultAddress)[0];
				let data = {
					address: this.textarea,
					privateKey: "",
					mnemonics: "",
					chainType: this.config.chainType,
					chainName: this.config.chainName,
					chainId: this.config.chainId,
					name: this.name || this.config.name,
					password: "",
					passwordTilp: "",
					importMethod: this.config.importMethod
				}
				let token = {
					address: this.textarea,
					chainType: this.config.chainType,
					chainName: this.config.chainName,
					chainId: this.config.chainId,
					tokenaddress: this.$config.defaultAddress,
					tokenname: result.name,
					tokenimg: "",
					tokennum: "0",
					tokendemail: result.decimal,
					tokensymbol: result.symbol,
					tokenprice: "1",
				}
				uni.$db.insert('list', 'choinList', token).then((res) => {
					uni.$db.insert('list', 'addressList', data).then((res) => {
						this.$store.commit('setAddress', this.textarea);
						this.$store.commit('setChainId', this.config.chainId);
						let rpclist = uni.getStorageSync('rpclist') || [];
						const foundChain = rpclist.find(chain => chain.chainId == this.config.chainId);
						this.$store.commit('setRpc', foundChain?.defultRPC);
						this.$updateWalletInfo()
						uni.switchTab({
							url: '/pages/index/index', // 这里的路径是 tabBar 页面在项目中的路径
							success() {},
							fail(err) {}
						});
					}).catch((err) => {
						return this.toast('钱包导入失败，请退出重新导入')
					});
				}).catch((err) => {
					return this.toast('钱包导入失败，请退出重新导入')
				});

			},
			pasteText() {
				uni.getClipboardData({
					success: (res) => {
						this.textarea = res.data;
					},
					fail() {}
				});
			},
			toast(msg) {
				uni.showToast({
					title: msg,
					position: "bottom",
					icon: 'none'
				});
			}
		}
	}
</script>
<script module="renderjs" lang="renderjs">
	export default {
		data() {
			return {
				jsLoadState: false,
				tjsLoadState: false,
				dataLoadState: false,
				config: {}
			}
		},
		mounted() {
			const ethersScript = document.createElement('script');
			ethersScript.src = 'static/script/ethers-5.2.umd.min.js';
			ethersScript.onload = async () => {
				this.jsLoadState = true;
			};
			document.head.appendChild(ethersScript);
			// 载入 TronWeb.js
			const tronWebScript = document.createElement('script');
			tronWebScript.src = 'static/script/newTronWeb.js';
			tronWebScript.onload = () => {
				this.tjsLoadState = true;
			};
			document.head.appendChild(tronWebScript);
		},
		methods: {
			getConfig(newValue) {
				if (newValue) {
					this.dataLoadState = true
					this.config = newValue;
				}
			},
			async checkAddress(e) {
				if (!e.currentTarget.dataset.checked) {
					return this.$ownerInstance.callMethod('toast', '请阅读并同意协议');
				}
				if (!e.currentTarget.dataset.address) {
					return this.$ownerInstance.callMethod('toast', '请输入钱包地址');
				}
				const address = e.currentTarget.dataset.address

				if (this.config.chainType == "ETH") {
					try {
						// 使用 ethers.utils.isAddress 方法验证地址
						if (ethers.utils.isAddress(address)) {
							return this.$ownerInstance.callMethod('confirm');
						}
					} catch (error) {
						// console.error('Error validating address:', error);
					}
				} else if (this.config.chainType == "TRON") {
					if (TronWeb.TronWeb.isAddress(address)) {
						return this.$ownerInstance.callMethod('confirm');
					}
				}
				this.$ownerInstance.callMethod('toast', "无效地址");
			},
		},
	}
</script>

<style lang="scss" scoped>
	.Observewallet {
		width: 100%;
		height: 100vh;
		background: #F6F6F6;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.placeholder {
			font-size: 20upx;
		}

		.contentBox {
			flex: 1;
			padding: 0 50upx;

			.textarea_box {

				height: 224upx;
				background: #FFF;
				border-radius: 20upx;
				padding: 24upx 26upx;
				margin-top: 40upx;

				.textarea {
					width: 100%;
					height: 188upx;
					box-sizing: border-box;
				}



				.controls {
					display: flex;
					font-size: 26upx;
					line-height: 36upx;
					color: #368521;
					font-weight: 400;
					flex-direction: row-reverse;

					.paste {
						padding: 0 20upx;
					}

					.keypal {
						padding: 0 20upx;
						border-right: 1px solid #D8D8D8;
					}
				}
			}

			.form-item {
				margin-top: 30upx;

				.title {
					font-size: 30upx;
					color: #3D3D3D;
				}

				.f28 {
					font-size: 28upx;
				}

				.iptStyle {
					border-radius: 20upx;
					background-color: #FFFFFF;

					.input {
						padding: 26upx 24upx;
						font-size: 26upx;
					}
				}

				.name-ipt {
					margin-top: 26upx;
				}

				.pass-ipt {
					margin-top: 26upx;
				}

				.confirm-pass-ipt {
					margin-top: 12upx;
				}

			}



			.mt {
				margin-top: 900upx;
			}


		}

		.btn_box {
			padding: 0 50upx 90upx;
			margin-top: 200upx;

			.protocol {
				display: flex;
				align-items: center;

				.raido-box {
					display: flex;

					.raido {
						width: 32upx;
						height: 32upx;
					}
				}

				.tilp {
					color: #8E8E8E;
					font-size: 26upx;
					margin-left: 10upx;

					.text {
						color: #297814;
					}
				}
			}

			.btn {
				font-size: 26upx;
				color: #F6F6F6;
				line-height: 88upx;
				background: linear-gradient(180deg, #CEF3D3 100%, #297814 61%);
				border-radius: 10upx;
				text-align: center;
				margin-top: 30upx;
			}

			.disabled {
				background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
			}
		}
	}
</style>